package com.huawei.jenkins.vss;

import com.google.common.base.Preconditions;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.smn.v2.SmnClient;
import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequest;
import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequestBody;
import com.huaweicloud.sdk.smn.v2.model.PublishMessageResponse;
import com.huaweicloud.sdk.smn.v2.region.SmnRegion;
import com.huaweicloud.sdk.vss.v3.VssClient;
import com.huaweicloud.sdk.vss.v3.model.*;
import com.huaweicloud.sdk.vss.v3.region.VssRegion;
import org.apache.commons.lang.StringUtils;
import hudson.model.TaskListener;

import java.io.Serializable;


public class vssService implements Serializable {
    private static final long serialVersionUID = 1;

    public static String CreateTasks(TaskListener listener, CustomInput customInput) {
        inputValidate(customInput);
        ICredential auth = new BasicCredentials()
                .withAk(customInput.getAk())
                .withSk(customInput.getSk());

        VssClient client = VssClient.newBuilder()
                .withCredential(auth)
                .withRegion(VssRegion.valueOf(customInput.getRegion()))
                .build();
        CreateTasksRequest request = new CreateTasksRequest();
        if (StringUtils.isNotBlank(customInput.getUpgrade())) {
            request.withUpgrade(Boolean.valueOf(customInput.getUpgrade()));
        }


        CreateTasksRequestBody body = new CreateTasksRequestBody();

        TaskSettingsTaskConfig taskConfigbody = new TaskSettingsTaskConfig();

        body.withUrl(customInput.getUrl());
        body.withTaskName(customInput.getTask_name());

        if (StringUtils.isNotBlank(customInput.getTask_type())) {
            body.withTaskType(CreateTasksRequestBody.TaskTypeEnum.fromValue(customInput.getTask_type()));
        }

        if (StringUtils.isNotBlank(customInput.getTask_period())) {
            body.withTaskPeriod(CreateTasksRequestBody.TaskPeriodEnum.fromValue(customInput.getTask_period()));
        }

        if (StringUtils.isNotBlank(customInput.getTimer())) {
            body.withTimer(customInput.getTimer());
        }

        if (StringUtils.isNotBlank(customInput.getTimer())) {
            body.withTimer(customInput.getTimer());
        }

        if (StringUtils.isNotBlank(customInput.getTrigger_time())) {
            body.withTriggerTime(customInput.getTrigger_time());
        }

        if (StringUtils.isNotBlank(customInput.getScan_mode())) {
            taskConfigbody.withScanMode(TaskSettingsTaskConfig.ScanModeEnum.fromValue(customInput.getScan_mode()));
        }

        if (StringUtils.isNotBlank(customInput.getPort_scan())) {
            taskConfigbody.withPortScan(Boolean.valueOf(customInput.getPort_scan()));
        }

        if (StringUtils.isNotBlank(customInput.getWeak_pwd_scan())) {
            taskConfigbody.withWeakPwdScan(Boolean.valueOf(customInput.getWeak_pwd_scan()));
        }

        if (StringUtils.isNotBlank(customInput.getCve_check())) {
            taskConfigbody.withCveCheck(Boolean.valueOf(customInput.getCve_check()));
        }

        if (StringUtils.isNotBlank(customInput.getText_check())) {
            taskConfigbody.withTextCheck(Boolean.valueOf(customInput.getText_check()));
        }

        if (StringUtils.isNotBlank(customInput.getPicture_check())) {
            taskConfigbody.withPictureCheck(Boolean.valueOf(customInput.getPicture_check()));
        }

        if (StringUtils.isNotBlank(customInput.getMalicious_code())) {
            taskConfigbody.withMaliciousCode(Boolean.valueOf(customInput.getMalicious_code()));
        }

        if (StringUtils.isNotBlank(customInput.getMalicious_link())) {
            taskConfigbody.withMaliciousLink(Boolean.valueOf(customInput.getMalicious_link()));
        }

        body.withTaskConfig(taskConfigbody);
        request.withBody(body);
        String message = "";
        try {
            CreateTasksResponse response = client.createTasks(request);
            listener.getLogger().println("创建扫描任务并执行：" + response.getInfoCode());

            listener.getLogger().println("任务状态：" + response.getTaskStatus());
            String taskStatus = response.getTaskStatus().toString();
            ShowTasksResponse showTasksResponse = null;
            while (taskStatus.equals("running") || taskStatus.equals("waiting") || taskStatus.equals("ready")) {
                showTasksResponse = showTasks(client, response.getTaskId(), listener);
                taskStatus = showTasksResponse.getTaskStatus().toString();
                try {
                    if (taskStatus.equals("running") || taskStatus.equals("waiting") || taskStatus.equals("ready")) {
                        Thread.currentThread().sleep(30000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (taskStatus.equals("success")) {
                listener.getLogger().println("安全分数：" + showTasksResponse.getScore());
                listener.getLogger().println("安全等级：" + showTasksResponse.getSafeLevel());
                listener.getLogger().println("高危漏洞数：" + showTasksResponse.getStatistics().getHigh());
                listener.getLogger().println("中危漏洞数：" + showTasksResponse.getStatistics().getMiddle());
                listener.getLogger().println("低危漏洞数：" + showTasksResponse.getStatistics().getLow());
                listener.getLogger().println("提示危漏洞数：" + showTasksResponse.getStatistics().getHint());

                if (StringUtils.isNotBlank(customInput.getTopicUrn())) {
                    //发送钉钉微信通知
                    publishMessage(customInput, showTasksResponse, listener);
                }

            }


        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            listener.getLogger().println("错误信息：" + e.getErrorMsg());
        }
        return message;
    }

    private static void inputValidate(CustomInput customInput) {
        final String ak = customInput.getAk();
        final String sk = customInput.getSk();
        final String region = customInput.getRegion();
        final String task_name = customInput.getTask_name();
        final String url = customInput.getUrl();
        Preconditions.checkArgument(StringUtils.isNotBlank(task_name), "task name can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(url), "url can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(region), "region can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(ak) && StringUtils.isNotBlank(sk), "Ak, Sk can not be blank");
    }


    public static ShowTasksResponse showTasks(VssClient client, String taskId, TaskListener listener) {
        ShowTasksRequest request = new ShowTasksRequest();
        request.withTaskId(taskId);
        ShowTasksResponse response = null;
        try {
            response = client.showTasks(request);
            listener.getLogger().println("任务进度：" + response.getProgress() + "%");
            listener.getLogger().println("任务状态：" + response.getTaskStatus());
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            listener.getLogger().println("错误信息：" + e.getErrorMsg());
        }
        return response;
    }

    public static void publishMessage(CustomInput customInput, ShowTasksResponse info, TaskListener listener) {
        ICredential auth = new BasicCredentials()
                .withAk(customInput.getAk())
                .withSk(customInput.getSk());

        SmnClient client = SmnClient.newBuilder()
                .withCredential(auth)
                .withRegion(SmnRegion.valueOf(customInput.getRegion()))
                .build();
        PublishMessageRequest request = new PublishMessageRequest();
        request.withTopicUrn(customInput.getTopicUrn());
        PublishMessageRequestBody body = new PublishMessageRequestBody();
        String url = "https://console.huaweicloud.com/vss/?region=" + customInput.getRegion() + "#/vss/manager/assetlist/domain";
        String message = "尊敬的华为云用户，您好：\n本次执行VSS漏洞扫描的结果：";
        message += "\n安全分数：" + info.getScore();
        message += "\n安全等级：" + info.getSafeLevel();
        message += "\n高危漏洞数：" + info.getStatistics().getHigh();
        message += "\n中危漏洞数：" + info.getStatistics().getMiddle();
        message += "\n低危漏洞数：" + info.getStatistics().getLow();
        message += "\n提示危漏洞数：" + info.getStatistics().getHint();
        message += "\n关于具体详情，可在：" + url + "\n中查看";
        body.withMessage(message);
        request.withBody(body);
        try {
            PublishMessageResponse response = client.publishMessage(request);
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            listener.getLogger().println("SMN服务消息发生失败，错误信息：" + e.getErrorMsg());
        }
    }


}
